from rest_framework import serializers, mixins, viewsets
from rest_framework.decorators import list_route
from rest_framework.response import Response
import os
from busness_manage import settings

import logging

from course.filters import CourseFilterSet
from course.models import CourseGroup, Course, RotationMap, PdfManage
from course.serializers import CourseGroupSerializer, CourseSerializer, RotationMapSerializer, PdfManageSerializer

logger = logging.getLogger('django')
# Create your views here.


class CourseGroupViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin,
                         mixins.ListModelMixin, viewsets.GenericViewSet):
    queryset = CourseGroup.objects.filter(is_delete=False).all()
    serializer_class = CourseGroupSerializer

    def create(self, request, *args, **kwargs):
        """
        创建新分类
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        group_name = request.data['group_name']
        if len(group_name) > 6 or len(group_name) < 2:
            raise serializers.ValidationError('分类限制在2-6个字')
        result = super().create(request)
        return Response(result.data)

    @list_route(['GET'])
    def del_group(self, request):
        group_id = request.query_params.get('group_id')
        course = Course.objects.filter(course_group_id=group_id, is_delete=False)
        if course:
            raise serializers.ValidationError('该分类下有课程，请修改课程的分类或者删除该分类下的课程后再试！')
        course_group = CourseGroup.objects.filter(id=group_id).first()
        course_group.is_delete = True
        course_group.save()
        return Response('删除成功')

    @list_route(['GET'])
    def get_all(self, request):
        """获取所有分类信息"""
        return Response(self.queryset.values())


class CourseViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin,
                    mixins.ListModelMixin, viewsets.GenericViewSet):
    queryset = Course.objects.filter(is_delete=False).all()
    serializer_class = CourseSerializer
    filter_class = CourseFilterSet

    @list_route(['GET'])
    def get_course(self, request):
        """按照分类获取课程信息"""
        group_id = request.query_params.get('group_id')
        if group_id:
            course = Course.objects.filter(is_delete=False, course_group_id=group_id).all()
        else:
            course = Course.objects.filter(is_delete=False).all()
        return Response(CourseSerializer(course, many=True).data)


class RotationMapViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin,
                         mixins.ListModelMixin, viewsets.GenericViewSet):
    queryset = RotationMap.objects.filter(is_delete=False).all()
    serializer_class = RotationMapSerializer

    def create(self, request, *args, **kwargs):
        """
        新增图片
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        max_order = self.queryset.order_by('-order').first()
        request.data['order'] = max_order.order + 1 if max_order else 1
        result = super().create(request)
        return Response(result.data)

    @list_route(['GET'])
    def get_banner(self, request):
        """获取所有轮播图"""
        return Response(self.queryset.values())


class PdfManageViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin,
                       mixins.ListModelMixin, viewsets.GenericViewSet):
    queryset = PdfManage.objects.filter(is_delete=False).all().order_by('pdf_name')
    serializer_class = PdfManageSerializer

    @list_route()
    def pdf_list_with_page(self, request, **kwargs):
        """获取列表(带分页)"""
        current_page = request.query_params.get('current_page', 1)
        start_page, end_page = (int(current_page) - 1) * 15, int(current_page) * 15
        school_name = request.query_params.get('school_name')
        results = self.queryset.filter(school_name=school_name)
        count = len(results)
        result = PdfManageSerializer(results[start_page:end_page], many=True)
        return Response({'result': result.data, 'current_page': current_page, 'count': count})

    @list_route()
    def pdf_list(self, request, **kwargs):
        """获取列表(不带分页)"""
        school_name = request.query_params.get('school_name')
        results = self.queryset.filter(school_name=school_name)
        result = PdfManageSerializer(results, many=True)
        return Response({'data': result.data})

    @list_route(['POST'])
    def pdf_upload(self, request, **kwargs):
        fp = request.FILES.get("file")
        if not fp:
            raise serializers.ValidationError('pdf文件为空')
        # 文件名
        pdf_name, school_name = request.data.get('pdf_name', ''), request.data.get('school_name')
        # fp 获取到的上传文件对象 -- 最外层放hs的文件；fd文件夹放fd大学的文件
        if school_name == 'hs':
            path = os.path.join(settings.MEDIA_ROOT, "%s" % pdf_name)  # 上传文件本地保存路径
        else:
            path = os.path.join(os.path.join(settings.MEDIA_ROOT, "fd"), "%s" % pdf_name)

        # 判断文件是否存在 存在则先删除
        if os.path.exists(path):
            os.remove(path)
        if fp.multiple_chunks():  # 判断上传文件大于2.5MB的大文件
            # 为真
            file_yield = fp.chunks()  # 迭代写入文件
            with open(path, 'wb') as f:
                for buf in file_yield:  # for情况执行无误才执行 else
                    f.write(buf)
        else:
            with open(path, 'wb') as f:
                f.write(fp.read())
        # 判断是生产还是本地
        host_ip = request.META.get("HTTP_X_FORWARDED_FOR") or request.META.get("REMOTE_ADDR")
        # 生产
        if host_ip != '127.0.0.1':
            # 服务器域名 + 图片路径
            if school_name == 'hs':
                path = 'https://shmtuglobal.com/media/' + pdf_name
            else:
                path = 'https://fdufisf.org.cn/media/' + pdf_name
        return Response({'path': path})

    @list_route(['POST'])
    def pdf_add_bulk(self, request, **kwargs):
        """批量上传pdf"""
        file_list = os.listdir(os.path.join(settings.MEDIA_ROOT, 'pdf'))
        for f in file_list:
            PdfManage.objects.create(pdf_path='http://m.natcourse.com/media/'+f, pdf_name=f,
                                     course_schedule='Monday to Friday',
                                     course_score='3', school_name='hs')
        return Response('ok')

    @list_route(['POST'])
    def pdf_update(self, request, **kwargs):
        """修改/删除pdf"""
        params = request.data
        pdf_id, pdf_name, course_schedule = params.get('id'), params.get('pdf_name'), params.get('course_schedule')
        course_score, school_name, is_delete = params.get('course_score'), params.get('school_name'), params.get('is_delete')
        instance = self.queryset.filter(id=pdf_id)
        if not instance:
            raise serializers.ValidationError('无效id')
        instance.update(pdf_name=pdf_name, course_schedule=course_schedule, course_score=course_score,
                        school_name=school_name, is_delete=is_delete)
        return Response('修改成功')
